package liuliu.throughwaring.ui.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;

import net.tsz.afinal.annotation.view.CodeNote;

import liuliu.custom.control.dialog.LLDialog;
import liuliu.custom.control.edittext.ImageEditText;
import liuliu.custom.control.edittext.SpinnerEditText;
import liuliu.custom.control.picker.DatePickerDialog;
import liuliu.custom.control.toolbar.TToolbar;
import liuliu.custom.method.Utils;
import liuliu.throughwaring.R;
import liuliu.throughwaring.adapter.CommonAdapter;
import liuliu.throughwaring.adapter.ViewHolder;
import liuliu.throughwaring.base.BaseActivity;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.ivsign.android.IDCReader.Cvr100bMYTask;
import com.ivsign.android.IDCReader.Cvr100bTask;
import com.ivsign.android.IDCReader.IDCReaderSDK;
import com.ivsign.android.IDCReader.IdcardInfoExtractor;
import com.ivsign.android.IDCReader.IdcardValidator;

import java.io.File;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import liuliu.throughwaring.control.add.police.person.IRegPersonView;
import liuliu.throughwaring.control.add.police.person.RegPersonListener;
import liuliu.throughwaring.model.AlarmModel;
import liuliu.throughwaring.model.BlueToothModel;
import liuliu.custom.model.CodeModel;
import liuliu.throughwaring.model.CompanyModel;
import liuliu.throughwaring.model.NationAlarmModel;
import liuliu.throughwaring.model.PersonModel;
import liuliu.throughwaring.service.NoticeHandlerService;
import liuliu.throughwaring.ui.map.DingWeiListener;

/**
 * Created by liuliu on 2015/11/19   9:25
 * 注册人员信息
 *
 * @author 柳伟杰
 * @Email 1031066280@qq.com
 */
public class RegPersonActivity extends BaseActivity implements IRegPersonView {
    public static RegPersonActivity mInstance;
    @CodeNote(id = R.id.reg_person_toolbar)
    TToolbar mToolbar;
    @CodeNote(id = R.id.reg_person_image, click = "onClick")
    ImageView img_iv;
    @CodeNote(id = R.id.reg_person_image2, click = "onClick")
    ImageView img_iv2;
    @CodeNote(id = R.id.reg_person_user_nation, click = "onClick")
    SpinnerEditText reg_person_user_nation;//民族
    @CodeNote(id = R.id.reg_person_jiaotong_gongju, click = "onClick")
    SpinnerEditText reg_person_jiaotong_gongju;//交通工具选择
    @CodeNote(id = R.id.reg_person_entry_time, click = "onClick")
    SpinnerEditText entry_time_txt;//入职时间
    @CodeNote(id = R.id.reg_person_operating_pancha, click = "onClick")
    ImageEditText txtpancha;//盘查原因
    @CodeNote(id = R.id.reg_person_name)
    ImageEditText user_name_txt;//人员姓名
    @CodeNote(id = R.id.reg_person_idcard)
    ImageEditText idcard_txt;//身份证号(15位或者18位)
    @CodeNote(id = R.id.reg_person_tel)
    ImageEditText tel_txt;//联系电话
    @CodeNote(id = R.id.reg_person_user_address)
    ImageEditText user_address_txt;//地址
    @CodeNote(id = R.id.reg_person_user_station)
    ImageEditText user_station_txt;//职务

    @CodeNote(id = R.id.reg_person_remark)
    ImageEditText remark_txt;//备注
    @CodeNote(id = R.id.reg_person_read_btn, click = "onClick")
    Button read_btn;//读卡
    @CodeNote(id = R.id.reg_person_save_btn, click = "onClick")
    Button save_btn;//保存
    PersonModel personModel;
    //右侧菜单
    @CodeNote(id = R.id.reg_person_right_menu_draw)
    DrawerLayout right_menu;//右侧菜单
    @CodeNote(id = R.id.right_menu_toolbar)
    TToolbar toolbar;
    @CodeNote(id = R.id.right_menu_listview)
    ListView mRightMenu;
    @CodeNote(id = R.id.reg_person_aboutcar_ll)
    LinearLayout reg_person_aboutcar_ll;//与盘查车辆有关的内容
    @CodeNote(id = R.id.reg_person_carpaiId_ie)
    ImageEditText reg_person_carpaiId_ie;//车牌号
    @CodeNote(id = R.id.reg_person_car_jiaId_ie)
    ImageEditText reg_person_car_jiaId_ie;//车架号
    @CodeNote(id = R.id.reg_person_carId_ie)
    ImageEditText reg_person_carId_ie;//车辆识别码
    @CodeNote(id = R.id.reg_person_cartype_ie)
    ImageEditText reg_person_cartype_ie;//品牌类型
    @CodeNote(id = R.id.reg_person_pancha_address)
    ImageEditText reg_person_pancha_address;//盘查地址
    List<CodeModel> mCodeListNation;
    List<CodeModel> mCodeListCar;
    DatePickerDialog datePickerDialog;
    RegPersonListener mListener;
    StringBuffer path = new StringBuffer();
    Bitmap bm = null;
    Bitmap bm2 = null;
    String transactionId = "0";
    CompanyModel companyModel;
    String CID = "";//用来接收传递过来的企业信息
    private LLDialog llDialog;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new DingWeiListener();
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    String person_path = "";
    boolean isFanHui = true;

    @Override
    public void initViews() {
        setContentView(R.layout.activity_reg_person);
        mInstance = this;
        llDialog = new LLDialog(mInstance);
        CID = getIntent().getStringExtra("CompanyId");
        transactionId = getIntent().getStringExtra("TransactionId");
        // 启动定位,还是从缓存取值
        LocationStart();
        //获得当前的企业信息并存储在Model中
        List<CompanyModel> list = finalDb.findAll(CompanyModel.class);
        companyModel = finalDb.findAllByWhere(CompanyModel.class, "CompanyId='" + CID + "'").get(0);
        personModel = new PersonModel();
        mListener = new RegPersonListener(this, this);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String nowTime = formatter.format(curDate);
        switch (companyModel.getCompanyType()) {
            case "Company"://从业人员
                mToolbar.setCenterTitle("从业人员添加");
                entry_time_txt.setVisibility(View.VISIBLE);
                user_station_txt.setVisibility(View.VISIBLE);

                entry_time_txt.setCenterTxt(nowTime);
                txtpancha.setVisibility(View.GONE);
                break;
            case "Free"://流动人员
                mToolbar.setCenterTitle("盘查人员添加");
                txtpancha.setVisibility(View.VISIBLE);
                entry_time_txt.setVisibility(View.GONE);
                user_station_txt.setVisibility(View.GONE);

                reg_person_jiaotong_gongju.setVisibility(View.VISIBLE);
                reg_person_pancha_address.setVisibility(View.VISIBLE);
//                reg_person_pancha_address.setText(Utils.ReadString("NowLocation"));
                reg_person_pancha_address.setText("河北省保定市竞秀区东风中路");
                break;
            case "Lease"://租赁人员
                mToolbar.setCenterTitle("租赁人员添加");
                entry_time_txt.setLeftTxt("入住日期");
                entry_time_txt.setCenterTxt(nowTime);
                txtpancha.setVisibility(View.GONE);
                user_station_txt.setVisibility(View.GONE);
                break;
        }
        initDatas();
    }

    //高德地图定位
    public void LocationStart() {

        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(true);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    @Override
    public void initEvents() {
        mToolbar.setLeftOnClick(new TToolbar.LeftOnClickListener() {
            @Override
            public void leftclick() {
                mInstance.finish();
            }
        });
        toolbar.setLeftOnClick(new TToolbar.LeftOnClickListener() {
            @Override
            public void leftclick() {
                drawerManager(1);
            }
        });
        mRightMenu.setVisibility(View.VISIBLE);
    }

    private void refushRightMenu(final int type) {
        List<CodeModel> mCode = new ArrayList<>();
        switch (type) {
            case 1://车辆信息
                mCode = mCodeListCar;
                break;
            case 2://民族
                mCode = mCodeListNation;
                break;
        }
        //左划菜单的Adapter
        mRightMenu.setAdapter(new CommonAdapter<CodeModel>(mInstance, mCode,
                R.layout.right_menu_item) {
            @Override
            public void convert(final ViewHolder holder, final CodeModel model, int position) {
                if (model.getValue() != null) {
                    holder.setText(R.id.right_menu_title, model.getValue());
                }
            }
        });

        //左划菜单项点击事件
        mRightMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                drawerManager(type);
                switch (type) {
                    case 1://交通工具
                        String trans = mCodeListCar.get(position).getValue();
                        if (trans.equals("机动车")) {
                            reg_person_aboutcar_ll.setVisibility(View.VISIBLE);
                        } else {
                            reg_person_aboutcar_ll.setVisibility(View.GONE);
                        }
                        reg_person_jiaotong_gongju.setCenterTxt(mCodeListCar.get(position).getValue());
                        break;
                    case 2://民族
                        reg_person_user_nation.setCenterTxt(mCodeListNation.get(position).getValue());
                        break;
                }
            }
        });
        //设置高度
        setListViewHeightBasedOnChildren(mRightMenu);
    }

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        //获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) { //listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0); //计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight() + listView.getDividerHeight() / 2; //统计所有子项+dividerheight的总高度
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() + 2)) + 80;
        //listView.getDividerHeight()获取子项间分隔符占用的高度
        //params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    //加载数据
    private void initDatas() {
        mCodeListNation = new ArrayList<>();
        mCodeListCar = new ArrayList<>();
        mCodeListNation = finalDb.findAllByWhere(CodeModel.class, "codeName='Code_Nation'");
        mCodeListCar = finalDb.findAllByWhere(CodeModel.class, "codeName='Code_TrafficType'");
        personModel.setPersonSex("1");
        personModel.setPersonNation("01");
        personModel.setPersonNative("110000");
        personModel.setPersonCardType("11");
        reg_person_user_nation.setCenterTxt("汉族");
        idcard_txt.AddChangeMethod(new EditChangedListener());
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.reg_person_user_nation://民族
                refushRightMenu(2);
                drawerManager(2);
                break;
            case R.id.reg_person_jiaotong_gongju://交通工具
                refushRightMenu(1);
                drawerManager(1);
                break;
            case R.id.reg_person_image:
                startCamera(11);
                break;
            case R.id.reg_person_image2:
                startCamera(12);
                break;
            case R.id.reg_person_read_btn://读取身份证
                if (Utils.ReadString("BlueToothName").equals("")) {
                    Utils.ToastShort(RegPersonActivity.this, "请检查蓝牙读卡设备设置！");
                    mUtils.IntentPost(BluetoothListActivity.class);//跳转登录
                } else {
                    onReadCardCvr();
                }
                break;
            case R.id.reg_person_entry_time:
                datePickerDialog = new DatePickerDialog(mInstance, "");
                datePickerDialog.datePickerDialog(entry_time_txt);
                break;
            case R.id.reg_person_save_btn:
                if (!checkCardId()) {
                    Utils.ToastShort(RegPersonActivity.this, "身份证号码错误");
                } else {
                    if (checkPersonSave()) {
                        String sqlType = "OnJob";
                        String type = "从业人员";

                        if (companyModel.getCompanyType().equals("Company")) {
                            type = "从业人员";
                            sqlType = "OnJob";
                        } else if (companyModel.getCompanyType().equals("Free")) {
                            type = "盘查人员";
                            sqlType = "";
                        } else {
                            type = "租赁人员";
                            sqlType = "CheckIn";
                        }
                        if (idcard_txt.getText().equals("130682199206033463")) {

                            finalDb.save(new AlarmModel(user_name_txt.getText(), type, "在逃", "130682199206033463", Utils.ReadString("PoliceId"), Utils.getRealTime()));
                            llDialog.setMiddleMessage("此人为A类“全国在逃人员”，请采取措施！！！ ");
                            llDialog.setMiddleMessageRed();
                            llDialog.setOnPositiveListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    // getPersonModel();
                                    //mListener.RegPerson(personModel);
                                    llDialog.dismiss();
                                    llDialog = null;
                                    mInstance.finish();
                                }
                            });
                            llDialog.show();
                        } else {
                            //是否有未离职信息
                            if (!sqlType.equals("")) {
                                String sql = "PersonCardId='" + idcard_txt.getText() + "' and PersonStatus='" + sqlType + "'";
                                final List<PersonModel> weiList = finalDb.findAllByWhere(PersonModel.class, sql);
                                if (weiList.size() > 0) {
                                    isFanHui = false;
                                    //提示有未离职退租的是否离职退租
                                    if (sqlType.equals("OnJob")) {
                                        llDialog.setMiddleMessage(user_name_txt.getText() + "未离职，是否离职并入职？");
                                    } else {
                                        llDialog.setMiddleMessage(user_name_txt.getText() + "未离店，是否离店并入住？");
                                    }
                                    llDialog.setRightButtonVal("放弃");
                                    llDialog.setLeftButtonVal("确定");
                                    final String finalSqlType = sqlType;
                                    llDialog.setOnPositiveListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {//点击确定按钮
                                            llDialog.cancel();
                                            //离职
                                            PersonModel person = weiList.get(0);
                                            if (finalSqlType.equals("OnJob")) {
                                                person.setPersonStatus("LeaveJob");
                                                personModel.setPersonStatus("LeaveJob");
                                            } else {
                                                person.setPersonStatus("CheckOut");
                                                personModel.setPersonStatus("CheckOut");
                                            }
                                            mListener.RegPerson(person);
                                            //保存
                                            getPersonModel();
                                            mListener.RegPerson(personModel);
                                        }
                                    });
                                    llDialog.setOnNegativeListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            llDialog.cancel();
                                        }
                                    });//点击取消按钮
                                    llDialog.show();
                                } else {
                                    getPersonModel();
                                    mListener.RegPerson(personModel);
                                }
                            } else {
                                getPersonModel();
                                mListener.RegPerson(personModel);
                            }
                        }
                    }
                }
                break;
        }
    }

    /*开启关闭左划菜单*/
    private void drawerManager(int i) {
        if (right_menu.isDrawerOpen(GravityCompat.END)) {
            right_menu.closeDrawer(GravityCompat.END);
        } else {
            right_menu.openDrawer(GravityCompat.END);
            String title = "";
            switch (i) {
                case 1:
                    title = "交通工具";
                    break;
                case 2:
                    title = "民族";
                    break;
            }
            toolbar.setCenterTitle(title);
        }


    }

    //cvr
    private void onReadCardCvr() {
        if (Utils.checkBluetooth(RegPersonActivity.this, 2)) {
            final ProgressDialog progressDialog = ProgressDialog.show(RegPersonActivity.this, "", "正在读取身份证信息...", true, false);
            final Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    Bundle bundle = msg.getData();
                    boolean find = false;
                    progressDialog.dismiss();
                    if (bundle != null) {
                        boolean result = bundle.getBoolean("result");
                        PersonModel person = (PersonModel) bundle.getSerializable("person_info");
                        if (result) {
                            find = true;
                            setPerson(person);
                        } else {
                            if (null != person) {
                                find = true;
                                Utils.ToastShort(RegPersonActivity.this, person.getPersonName());
                            }
                        }
                    }
                    if (!find) {
                        Utils.ToastShort(RegPersonActivity.this, "证件读取失败！（cvr）");
                    }
                }
            };

            new Cvr100bMYTask().startCvr100bTask(mInstance, new Cvr100bTask.Cvr100bListener() {
                @Override
                public BlueToothModel reauestBlueDevice() {
                    BlueToothModel blue = new BlueToothModel();
                    blue.setDeviceAddress(Utils.ReadString("BlueToothName"));
                    return blue;
                }

                @Override
                public void onResult(boolean result, PersonModel person) {
                    Message msg = handler.obtainMessage(1);
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("result", result);
                    bundle.putSerializable("person_info", person);
                    msg.setData(bundle);
                    msg.sendToTarget();
                }
            });
        } else {
            Utils.ToastShort(RegPersonActivity.this, "请检查蓝牙读卡设备设置！");
        }
    }

    private String getCodeVlaue(List<CodeModel> list, String name) {
        for (CodeModel c : list) {
            if (c.getName().equals(name)) {
                return c.getValue();
            }
        }
        return "";
    }

    private String getCodeName(List<CodeModel> list, String value) {
        for (CodeModel c : list) {
            if (c.getValue().equals(value)) {
                return c.getName();
            }
        }
        return "";
    }

    private void setPerson(PersonModel person) {
        idcard_txt.setText(person.getPersonCardId());
        user_name_txt.setText(person.getPersonName());
        user_address_txt.setText(person.getPersonAddress());
        if (person.getPersonCardImage() != null) {
            if (!person.getPersonCardImage().equals("")) {
                Bitmap bitmap = Utils.getBitmapByte(person.getPersonCardImage());
                img_iv.setImageBitmap(bitmap);
                personModel.setPersonImgUrl(person.getPersonImgUrl());
            }
        } else {
            Utils.ToastShort(RegPersonActivity.this, "照片解码失败！");
        }
        reg_person_user_nation.setCenterTxt(getCodeVlaue(mCodeListNation, person.getPersonNation()));//民族
        reg_person_jiaotong_gongju.setCenterTxt(getCodeVlaue(mCodeListCar, person.getTrafficType()));//交通工具
    }

    private String sexid = "";//性别编码
    private String nativeid = "";//籍贯编码

    private void getPersonModel() {

        personModel.setPersonCardType("11");
        personModel.setPersonNation(getCodeName(mCodeListNation, reg_person_user_nation.getCenterText()));
        personModel.setPersonSex(sexid);
        personModel.setPersonAddress(user_address_txt.getText());
        personModel.setPersonCardId(idcard_txt.getText());
        personModel.setPersonCompanyId(companyModel.getCompanyId());
        personModel.setPersonComapnyName(companyModel.getCompanyName());
        personModel.setPersonComapnyType(companyModel.getCompanyType());
        personModel.setPersonComment(remark_txt.getText());
        personModel.setPersonTransactionId(transactionId);
        personModel.setPersonPoliceId(Utils.ReadString("PoliceId"));
        personModel.setPersonPhoneNumber(tel_txt.getText());
        personModel.setPersonId("");
        personModel.setPersonNative(nativeid);
        personModel.setPersonCreateTime(Utils.getTodayFullString());
        //personModel.setJob(operating_post_txt.getText());

        personModel.setCheckReason(txtpancha.getText());
        if (companyModel.getCompanyType().equals("Company")) {
            personModel.setCheckInTime(Utils.changDatetoGeshi(entry_time_txt.getCenterText()));
            personModel.setPersonStatus("OnJob");
        } else if (companyModel.getCompanyType().equals("Lease")) {
            personModel.setPersonStatus("CheckIn");
            personModel.setCheckInTime(entry_time_txt.getCenterText());
        } else {
            personModel.setPersonStatus("None");
        }
        personModel.setOffice(user_station_txt.getText());
        personModel.setPersonName(user_name_txt.getText().trim());
        if (bm != null) {
            personModel.setPersonCardImage(Utils.encodeBitmap(bm));
        } else {
            personModel.setPersonCardImage("");
        }
        personModel.setCheckReason(txtpancha.getText());//盘查原因
        personModel.setCheckAddress(reg_person_pancha_address.getText());//盘查地址
        personModel.setTrafficType(getCodeName(mCodeListCar, reg_person_jiaotong_gongju.getCenterText()));//交通工具类型
        personModel.setVehiclePlateNumbers(reg_person_carpaiId_ie.getText());//车牌号
        personModel.setVehicleFrameNumber(reg_person_car_jiaId_ie.getText());//车架号
        personModel.setVehicleIdentificationNumber(reg_person_carId_ie.getText());//车辆识别码
        personModel.setVehicleBrandNumber(reg_person_cartype_ie.getText());//品牌类型
        isFanHui = true;
    }

    private boolean checkPersonSave() {
        if (user_name_txt.getText().equals("")) {
            mUtils.ToastShort("姓名不能为空");
            return false;
        } else if (tel_txt.getText().equals("")) {
            mUtils.ToastShort("电话不能为空");
            return false;
        } else if (idcard_txt.getText().equals("")) {
            mUtils.ToastShort("证件号码不能为空");
            return false;
        } else {
            switch (companyModel.getCompanyType()) {
                case "Company":
                    if (user_station_txt.getText().equals("")) {
                        mUtils.ToastShort("职务不能为空");
                        return false;
                    }
                    if (user_address_txt.getText().equals("")) {
                        mUtils.ToastShort("人员住址不能为空");
                        return false;
                    }
                    break;
                case "Free":
                    if (txtpancha.getText().equals("")) {
                        mUtils.ToastShort("盘查原因不能为空");
                        return false;
                    }
                    break;
            }
            return true;
        }
    }

    @Override
    public void onRegPersonResult(boolean isTrue, String mes) {
        if (isFanHui) {
            Intent intent = new Intent();
            intent.putExtra("result", isTrue);
            this.setResult(131, intent);//返回页面1
            this.finish();
        } else {
            isFanHui = true;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 12 && resultCode == 12) {
            String name = data.getStringExtra("CodeAreaName");
            String value = data.getStringExtra("CodeAreaValue");
            personModel.setPersonNative(name);
        }
        if (requestCode == 11 && resultCode == -1) {
            bm = Utils.getimage(this, path.toString());
            person_path = path.toString();
            if (bm != null) {
                img_iv.setImageBitmap(Utils.centerSquareScaleBitmap(bm, 60));
                img_iv.setTag(bm);
            } else {
                img_iv.setImageResource(R.mipmap.person_header);
                img_iv.setTag(bm);
            }
            personModel.setPersonImgUrl(path.toString());
        }
        if (requestCode == 12 && resultCode == -1) {
            bm2 = Utils.getimage(this, path.toString());
            if (bm2 != null) {
                img_iv2.setImageBitmap(Utils.centerSquareScaleBitmap(bm2, 60));
                img_iv2.setTag(bm2);
            } else {
                img_iv2.setImageResource(R.mipmap.main_add_img);
                img_iv2.setTag(bm2);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //开启拍照
    public void startCamera(int type) {
        // 利用系统自带的相机应用:拍照
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        path = new StringBuffer();
        path.append(RegPersonActivity.this.getExternalFilesDir(null)).append("/" + Utils.getImgUrlByTime() + ".jpg");
        File file = new File(path.toString());
        Uri uri = Uri.fromFile(file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, type);
    }

    private boolean checkCardId() {
        boolean result = false;
        try {
            String card_id = idcard_txt.getText().toString();
            if (!Utils.isEmptyString(card_id)) {
                IdcardValidator iv = new IdcardValidator();
                if (!iv.isValidatedAllIdcard(card_id)) {
                    idcard_txt.setCenterTextRedColor();
                } else {
                    IdcardInfoExtractor iie = new IdcardInfoExtractor(card_id);
                    sexid = iie.getGender();
                    nativeid = iie.getNativeCode();
                    personModel.setPersonBirthday(String.format("%04d-%02d-%02d",
                            iie.getYear(), iie.getMonth(), iie.getDay()));
                    result = true;
                    idcard_txt.setCenterTextRedColor2();
                }
            }
        } catch (Exception e) {
            idcard_txt.setCenterTextRedColor();
            result = false;
        }
        return result;
    }

    class EditChangedListener implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            checkCardId();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bm != null) {
            if (!bm.isRecycled()) {
                bm.recycle();//回收图片所占的内存
                System.gc();
            }
        }
    }
}
